package thread;

class MyBlockQueue {

    private int[] items = new int[1000];
    volatile private int front;
    volatile private int rear;
    volatile private int size;

    // 入队列
    synchronized public void put(int elem) throws InterruptedException {
        if (size == items.length) {
            // 队列满了
            //return;
            this.wait();
        }
        // 把新元素放到 tail 所在位置上
        items[rear] = elem;
        rear++;
        // 万一tail达到末尾，就需要让tail从头再来
        if (rear == items.length) {
            rear = 0;
        }
        size++;
        this.notify();
    }


    // 出队列
    synchronized public Integer take() throws InterruptedException {
        if (size == 0) {
            this.wait();
        }
        int value = items[front];
        front++;
        if (front == items.length) {
            front = 0;
        }
        size--;
        this.notify();
        return value;
    }
}

public class Demo17 {
    public static void main(String[] args) {
        MyBlockQueue queue = new MyBlockQueue();
        // 生产者
        Thread t1 = new Thread(()->{
            int value = 0;
            while (true){
                try {
                    System.out.println("生产元素：" + value);
                    queue.put(value);
                    value++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        // 消费者
        Thread t2  = new Thread(()->{
            while (true){
                try {
                    int value = 0;
                    value = queue.take();
                    System.out.println("消费元素：" + value);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();

    }
}
